package org.rcloud.io.controller;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2019/3/11.
 */

@Controller
public class PhotographyController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PhotographyController.class);


    //配置文件的路径
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @GetMapping("/photography")
    public String upload() {
        return "photography";
    }
    @PostMapping("/photography")
    @ResponseBody
    public String upload(@RequestParam( value="files",required=false ) MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        //获取文件名
        String fileName =String.valueOf(System.currentTimeMillis())+file.getOriginalFilename();
        //获取文件前缀名
        //String caselshName = fileName.substring(0,fileName.lastIndexOf("."));
        //获取文件后缀名
        //String caselshTyle=fileName.substring(fileName.lastIndexOf("."),fileName.length());

        File dest = new File(uploadFolder +"images1/"+ fileName);
        try {
            file.transferTo(dest);

            /*scale是可以指定图片的大小，值在0到1之间，1f就是原图大小，0.5就是原图的一半大小，
            这里的大小是指图片的长宽。
            而outputQuality是图片的质量，值也是在0到1，越接近于1质量越好，越接近于0质量越差。*/

            //服务器路径
            Thumbnails.of(dest).size(750, 450).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(uploadFolder +"images/shui.jpg")), 0.3f).outputQuality(0.5f).toFile(uploadFolder +"images2/"+ fileName);

            LOGGER.info(uploadFolder +"images2/"+ fileName);

            return "https://wdsx.fywljt.cn/wechat-api-0.0.1-SNAPSHOT/upload/images2/"+ fileName;

        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上传失败！";
    }


}
